package com.sita.bike.ui.activity.roadtrust;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sita.bike.R;
import com.sita.bike.event.TrackSaveEvent;
import com.sita.bike.persistence.Route;
import com.sita.bike.persistence.RouteData;
import com.sita.bike.rest.model.LocType;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.RouteNewRequest;
import com.sita.bike.rest.model.RouteNewResponse;
import com.sita.bike.support.Constants;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.bike.utils.RetrofitUtils;
import com.squareup.okhttp.OkHttpClient;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.OkClient;
import retrofit.client.Response;
import retrofit.converter.GsonConverter;
import retrofit.http.Body;
import retrofit.http.POST;

/**
 * Created by manhongyun on 15/11/18.
 */
public class RoadTrustSaveTrackActivity extends Activity implements View.OnClickListener {
    private Button btnSave;
    private long mTrackId;
    private Route mRoute;
    private EditText mTrackName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTrackId = getIntent().getLongExtra("trackId", -1);
        setContentView(R.layout.activity_road_trust_save_track);
        btnSave = (Button) findViewById(R.id.activity_road_trust_track_save_button);
        btnSave.setOnClickListener(this);
        mTrackName = (EditText) findViewById(R.id.road_trust_save_track_name_value);
        mRoute = new Route();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.activity_road_trust_track_save_button) {
            mRoute.setId(mTrackId);
            mRoute.setDescription(mTrackName.getText().toString());
            PersistUtils.updateRoute(mRoute);
            uploadRoute();
            EventBus.getDefault().post(new TrackSaveEvent(TrackSaveEvent.ACTION_SAVE));
            this.finish();

        }
    }

    @Override
    public void onBackPressed() {
        // remove the temp route
        if (mTrackId != -1) {
            PersistUtils.deleteRouteData(mTrackId);
            PersistUtils.deleteRoute(mTrackId);
        }
        EventBus.getDefault().post(new TrackSaveEvent(TrackSaveEvent.ACTION_CANCEL));
        super.onBackPressed();
    }

    public interface CreateRouteService {

        @POST("/roadtrust/v1/routes/new")
        void createRoute(@Body RouteNewRequest params, Callback<RouteNewResponse> callback);
    }


    // Get the resource list
    private void uploadRoute() {

        String BASE_URL = Constants.BASE_URI;
        RequestInterceptor restInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Content-Type", Constants.APPLICATION_JSON);
                request.addHeader("Accept", Constants.APPLICATION_JSON);
            }
        };

        Gson gson = new GsonBuilder()
                .create();

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setEndpoint(BASE_URL)
                .setConverter(new GsonConverter(gson))
                .setRequestInterceptor(restInterceptor)
                .setClient(new OkClient(okHttpClient))
                .build();

        CreateRouteService service = restAdapter.create(CreateRouteService.class);

        RouteNewRequest rnr = new RouteNewRequest();
        // TODO get the real account id
        rnr.mAccountId = AccountUtils.getAccountID();
        rnr.mCreateDate = String.valueOf(System.currentTimeMillis());
        rnr.mLocations = new ArrayList<>();
        List<RouteData> locs = PersistUtils.getRouteDataList(mTrackId);
        for (RouteData loc : locs
                ) {
            Location l = new Location();
            l.latitude = String.valueOf(loc.getLatitude());
            l.longitude = String.valueOf(loc.getLongitude());
            l.locType = LocType.GCJ02; // TODO modify the field of loctype in GPSLocations
            l.time = loc.getTime().toString();
            rnr.mLocations.add(l);
        }

        service.createRoute(rnr, new Callback<RouteNewResponse>() {
            @Override
            public void success(RouteNewResponse routeNewResponse, Response response) {
                if (response.getStatus() == 200 &&
                        routeNewResponse.mErrorCode.equals("0")) {
                    if (routeNewResponse.mData.mRouteId != 0) {
                        Toast.makeText(RoadTrustSaveTrackActivity.this, getResources().getText(R.string.upload_ok), Toast.LENGTH_LONG).show();

                        mRoute.setServerRouteId(String.valueOf(routeNewResponse.mData.mRouteId));
                        PersistUtils.updateRoute(mRoute);
                    }
                }
                Log.d("response", response.getReason());
            }

            @Override
            public void failure(RetrofitError error) {
                RetrofitUtils.displayError(RoadTrustSaveTrackActivity.this, error);
                Log.d("response", error.getMessage());
            }
        });
    }
}
